#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <sys/epoll.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <dirent.h>
#include <sys/stat.h>
#include <signal.h>
#include <ctype.h>
#define MAXSIZE 2000

#include "http/http.h"
#include "http/redirect.h"
#include "conf/parser.h"
#include "conf/debug.h"

const char *CONFIG = "/home/dandelight/workspace/server/engig/example/nginx.conf";

void dump_data()
{
  char msg[] = "exit received, dumping data...\n";
  if (write(STDERR_FILENO, msg, strlen(msg)) < 0)
  {
    perror("write failed");
    exit(0);
  }
  int fd = open("dump.dat", O_CREAT | O_WRONLY, 0744);
  if (write(fd, msg, strlen(msg)) < 0)
  {
    perror("write failed");
    exit(0);
  }
  fprintf(stderr, "done\n");
}

void say_hello(int port, const char *path)
{
  printf("We are now listening at port %d, location: %s\n", port, path);
  printf("Hello, server!\n");
}

int main(int argc, const char *argv[])
{
  int port = 9898;
  const char *path;
  struct conf_http *http;

  pid_t childs[8] = {0};
  pid_t this_pid = getpid();
  int n_servers = 1;

  if (argc < 2)
  {
    printf("Please specify full path to nginx.conf as argument.\n");
    printf("Commandline not specified, reading from configure file %s\n", CONFIG);
  }
  else
  {
    CONFIG = argv[1];
  }
  http = read_conf_file(CONFIG);
    
  for (n_servers = 0; n_servers < http->server_num; ++n_servers)
  {
    pid_t pid = fork();
    if (pid < 0)
    {
      perror("fork failed");
      exit(-1);
    }
    else if (pid == 0)
      break;
    else
    {
      childs[n_servers] = pid;
    }
  }
  

  if (n_servers != http->server_num)
  {
    // 修改工作目录
    struct conf_http_server *this_server = http->servers[n_servers];
    port = this_server->listen;
    path = this_server->location.map_to;
    if(this_server->location.type == SERVER_ROOT) {
      int ret = chdir(path);
      if (ret == -1)
      {
        perror("切换目录发生错误");
        exit(1);
      }
      run_epoll(port, path, this_server->location.from);
    }
    else {
      printf("%s", this_server->location.from);
      run_redirect(this_server->listen, this_server->location.from, NULL, NULL);
    }
  }
  else
  {
    for(int i=0; i<n_servers; ++i) {
      printf("%d\n", childs[i]);
    }
    while(true) {
      char input[128];
      fgets(input, 128, stdin);
      if (strncmp("exit", input, 4) == 0)
      {
        dump_data();
        destroy_http_server(http);
        for (int i = 0; i < n_servers; ++i)
        {
          printf("Killing %d\n", childs[i]);
          int ret = kill(childs[i], SIGINT);
          if(ret == -1) {
            perror("Kill failed");
          }
        }
        exit(0);
      }
    }
  }
  return 0;
}
